<template>
    <div>
      <!-- <div style="margin-left:20px;padding: 0px 0px;display:flex;border-bottom:1px solid #ddd;">
        <div style="padding: 20px 0px;font-family:500">
          审计整改材料提炼
        </div>
      </div> -->
      <div class="content"  style="padding-left:20px">
          <div class="left-box">

             <div style="margin:20px 0px">
                 <el-button type="primary" size="small"  @click="newDilog" plain>开启新对话</el-button>
              </div>
              <el-table
              ref="myTable"
              :data="hisData"
              highlight-current-row
              max-height="500px"
              @current-change="handleCurrentChange"
              >
              <el-table-column
                prop="date"
                label="历史列表"
                >
                <template #default="{ row }">
                  <div style="display:flex;align-items:center;justify-content:space-between">
                    <div>
                      {{formatDate(row.createdAt)}}
                    </div>
                    <div>
                       <!-- <el-button type="text" icon="el-icon-delete" circle style="color:#F56C6C" @click.stop="deleteData(row.id,row.status)" v-if="row.status=='PENDING'"></el-button> -->
                    </div>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div class="right-box"  style="padding-top:20px;max-width:800px;">
            <div class="upload" v-show="!hisFlag">
              <el-upload
              :headers="headers"
                class="upload-demo"
                ref="upload"
                name="file"
                :timeout="300000"
              :action="action"
              :multiple="true"
              :on-success="handleSuccess"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :file-list="fileList">
              <el-button slot="trigger"  type="primary" size="small">选取文件</el-button>
              <el-button style="margin-left: 10px;"  size="small" type="warning" @click="submitUpload"  
              >整改提炼</el-button>
              <span style="padding-left:20px;font-size:14px;color:#8492A6">只能上传word文件</span>
              </el-upload>
            </div>
            <div style="margin:20px 0px;font-size:14px;color:#606266" v-show="!hisFlag">
                提醒：本内容由AI智能审计管理系统生成
            </div>
            <div style="margin:20px 0px;font-size:14px;color:#606266" v-show="hisFlag && files.length>0">
              <span v-for="(item, index) in files"
              :key="index">
                {{item.originalFilename?item.originalFilename:''}}<span v-if="files.length>1 && index!=files.length-1">,</span>
              </span>
              
            </div>
            <div style="margin:20px 0px;" v-if="hisFlag">
                            <el-alert title="格式检查已完成" type="success" effect="dark" :closable="false" v-if="state=='COMPLETED'"></el-alert>
                            <el-alert title="格式检查等待处理" type="info" effect="dark" :closable="false" v-if="state=='PENDING'"></el-alert>
                            <el-alert title="格式检查处理中"  type="warning" effect="dark" :closable="false" v-if="state=='PROCESSING'"></el-alert>
                            <el-alert title="格式检查已失败" type="error" effect="dark" :closable="false" v-if="state=='FAILED'"></el-alert>
                      </div>
             <div  class="code">
                <vue-markdown :source="result"></vue-markdown>
              </div>
              <el-button  size="small" @click="copyClick(result)"  v-if="hisFlag && result">复制完整内容</el-button>
              <el-button  size="small" type="danger"   @click="deleteData()" v-if="state=='PENDING'">取消任务排队</el-button>
            <!-- <el-button type="success" :disabled="bookid==''" style="width:360px;height:50px"  @click="downLoad">立即下载</el-button> -->
          </div>
      </div>
    </div>
</template>
<script>
import VueMarkdown from 'vue-markdown';
import { formatDateTime } from '@/tools/index'
export default {
  name: 'waterworks-home',  
  data(){
    return{
      loading:false,
      hisData:[],
      result:'',
      bookid:'',
      fileList:[],
      action:'/api/services/hzsfjtai/file/uploadFile',
      hisFlag:false,
      type:'RECTIFICATION',
      state:'',
      timeoutId:null,
      fileListData:[],
      files:[],
      delId:''
    }
  },
  computed: {
    headers(){
      const sessionId = localStorage.getItem('X-Token');
      const projectId = localStorage.getItem('projectId');
        return{
          'X-Token':sessionId,
          'projectId':projectId
        };
    },
  },
  components: {
    VueMarkdown
  },
  created(){
    this.getHisData(false);
  },
  methods:{
    copyClick(text) {
        this.$copyText(text).then(() => {
            this.$message.success('复制成功');
        }).catch(() => {
            this.$message.warning('复制失败');
        });
    },
    newDilog(){
      clearTimeout(this.timeoutId);
      this.$refs.myTable.setCurrentRow()
      this.$refs.upload.clearFiles();//删除所有上传的文件
      this.hisFlag=false;
      this.result='';
      this.bookid='';
    },
    formatDate(time){
      console.log(99,time);
      return formatDateTime(time);
    },
    deleteData(){
      this.$confirm('取消任务排队将无法恢复，确认取消？').then(_ => {
          if(this.state!="PENDING"){
            this.$message.warning('当前任务状态已发生变更');
          }else{
            this.$axios.delete('/api/services/hzsfjtai/task/delete?id='+this.delId, {}).then(res => {
            if (res.data.code === 200) {
              this.$message.success('取消成功');
              this.getHisData(false);
            } else {
              this.$message(res.data.message)
            }
          }).catch(err => {
            this.$message.error(err)
          })
          }
      }).catch(_ => {});
    },
    handleCurrentChange(val) {
      if(val){
        clearTimeout(this.timeoutId);
        this.hisFlag=true;
        this.$axios.get('/api/services/hzsfjtai/task/getDesc?id='+val.id, {}).then(res => {
          if (res.data.code === 200) {
            this.delId=res.data.data.id;
            this.result =res.data.data.taskResponseData? res.data.data.taskResponseData:'';
            this.files =res.data.data.taskData? JSON.parse(res.data.data.taskData).files:'';
            this.state=res.data.data.status;
            // this.bookid =res.data.data.taskResponseData? JSON.parse(res.data.data.taskResponseData).id:'';
             let _this=this;
            if(_this.state!="COMPLETED"  &&  _this.state !="TIMEOUT"  &&  _this.state !="FAILED"){
             _this.timeoutId =   setTimeout(() => {
                    _this.handleCurrentChange(val); // 递归调用
                }, 3000);
            }else{
              val.status=_this.state
            }
          } else {
            this.$message(res.data.msg)
          }
        }).catch(err => {
          this.$message.error(err)
        })
      }
      
    },
    //获取历史数据
    getHisData(checkFlag){
      this.$axios.get('/api/services/hzsfjtai/task/getList?taskType='+this.type, {}).then(res => {
        if (res.data.code === 200) {
          this.hisData=res.data.data;
          if(checkFlag){
            this.$nextTick(()=>{
              this.$refs.myTable.setCurrentRow(this.hisData[0])
              this.loading=false
            })
          }
        } else {
          this.$message(res.data.msg)
        }
      }).catch(err => {
        this.$message.error(err)
      })
    },
     handleSuccess(response, file) {
      //  this.$refs.upload.clearFiles(); 
       if(response.code==200){
         // 处理上传成功的逻辑
          console.log('上传成功', response, file);
          this.fileListData.push(response.data);
          this.$message.success('上传成功！'); // 使用 Element UI 的消息提示
       }else{
         this.$message.error("上传失败")
       }
      
      
    },
    submitUpload() {
       if(this.fileListData.length==0){
            this.$message.warning("请先上传文件！")
            return
        }
      this.$axios.post('/api/services/hzsfjtai/llm/rectification', {fileMetadataList:this.fileListData}).then(res => {
            if (res.data.code === 200) {
              this.getHisData(true);
              this.fileListData=[];
            } else {
              this.$message(res.data.msg)
            }
          }).catch(err => {
            this.$message.error(err)
          })
      },
      handleRemove(file, fileList) {
        console.log(file, fileList);
      },
      handlePreview(file) {
        console.log(file);
      },
      // 限制上传数量
      // handleExceed(files, fileList) {//files指的是你刚上传的文件，fileList指的是你上传之前的文件数组
      //     this.$set(fileList[0], 'raw', files[0]);//raw就是指文件
      //     this.$set(fileList[0], 'name', files[0].name);//name就是指文件名
      //     this.$refs.upload.clearFiles();//删除所有上传的文件
      //     this.$refs.upload.handleStart(files[0]);//handleStart()指的是手动选择文件，Element Plus 的el-upload有说明
      // },
    // putFile(){
    //   this.bookid=''
    // },
    // downLoad(){
    //   window.location.href="/api/services/hzsfjtai/file/downloadFile/"+this.bookid
    // },
    exit(){
      this.$router.push({ path: '/dashboard' })
    },
  },
  mounted() {
  }
}
</script>
<style scoped lang="less" >
.code{
  width: 80%;
  margin: 30px 0px;
  min-height: 240px;
  padding: 30px;
  line-height: 40px;
  white-space: pre-wrap;       /* 允许元素内的文本换行 */
  background-color: #f4f4f4;
    border: 1px solid #ddd;
    padding: 10px;
    overflow: auto;
    font-family: 'Courier New', Courier, monospace;
}
/deep/ .el-table .el-table__row:hover {
  cursor: pointer; /* 这里可以更改为其他的光标样式，比如 'crosshair', 'help', 'move', 'not-allowed' 等 */
}
</style>

